<template>
  <div class="guide_page">
    <van-nav-bar
      :title="`请${isSelect ? '选择以前输入的' : '输入'}渠道`"
      left-arrow
      @click-left="$router.back()"
    />

    <div v-show="!isSelect">
      <van-row type="flex"
               justify="space-between"
               style="background-color: #FFFFFF"
               align="center"
      >
        <van-col span="20">
          <van-field autocomplete="off"
            v-model="inputValue"
            label="注册来源名称"
            required
            placeholder="请输入推广人姓名或者广告地址名称"
            type="textarea"
            rows="2"
            autosize
            clearable
            @clear="clearInputValue"
          />
        </van-col>
        <van-col span="4" style="text-align: right; padding-right: 6px;">
          <van-button
            size="small" type="info" @click.stop="addChannel"
          >添加</van-button>
        </van-col>
      </van-row>

      <div style="margin: 36px 16px 16px 16px;">
        <van-button round block
                    type="info"
                    :disabled="!newChannelObj.id"
                    @click.stop="toGenerateLinkOrCode"
        >带渠道，统计推广数据，生成{{ source_type === 'L' ? '链接' : '二维码'}}</van-button>
      </div>
    </div>

    <div v-show="isSelect">
      <van-field autocomplete="off"
        readonly
        clickable
        name="picker"
        :value="value"
        label="以前的渠道"
        placeholder="点击选择以前的渠道"
        @click="showPicker = true"
      />
      <div style="margin: 36px 16px 16px 16px;">
        <van-button round block
                    type="info"
                    :disabled="!value"
                    @click.stop="toGenerateLinkOrCode"
        >带渠道，统计推广数据，生成{{ source_type === 'L' ? '链接' : '二维码'}}</van-button>
      </div>
      <van-popup v-model="showPicker"
                 position="bottom"
                 :style="{ height: '60%' }"
      >
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="showPicker = false"
          value-key="name"
        />
      </van-popup>
    </div>

    <div style="margin: 46px 16px 16px 16px; ">
      <van-button
        round block
        type="primary"
        @click.stop="toGenerateLinkOrCode(false)"
      >不带渠道，不统计推广数据，生成{{ source_type === 'L' ? '链接' : '二维码'}}</van-button>
    </div>



    <van-divider
      @click="importChannel"
      v-show="true"
      :style="{
      color: !isSelect ? '#EE0A24': '#1989fa',
      fontWeight: 'bolder',
      borderColor: !isSelect ? '#EE0A24': '#1989fa',
      padding: '0 16px',
      marginTop: '160px',
    }"
    >
      {{ !isSelect ? `以前填写过渠道，生成${source_type === 'L' ? '链接' : '二维码'} >`: '< 填写新渠道'}}
    </van-divider>

  </div>
</template>

<script>
import {Dialog, Toast} from "vant";
import {mapGetters} from "vuex";
import {base_url,base_url_company} from "../../constants/comUtils";

export default {
  name: "guide",
  data(){
    return {
      base_url: base_url,
      base_url_company:base_url_company,
      inputValue: '',
      isSelect: false,
      historical_channel_list: [],

      value: '',
      columns: [
        {
          id: '001',
          text: '杭州',
        },
        {
          id: '002',
          text: '宁波',
        },
        {
          id: '003',
          text: '温州',
        },
        {
          id: '004',
          text: '嘉兴',
        },
        {
          id: '005',
          text: '湖州',
        },
      ],
      showPicker: false,
      // 新建的
      newChannelObj: {},
      // 选择的
      selectChannelObj: {},
      source_type: '',


    }
  },

  computed: {
    ...mapGetters(['allUserInfo'])
  },

  created() {
    if(this.$route.query.source_type){
      this.source_type = this.$route.query.source_type;
      this._getChannelArr();
    } else {
      this.$router.back();
    }
  },

  methods: {
    async _getChannelArr(){
      const res = await this.$api.others.reqChannelArr();
      if (res.code === 200){
        this.historical_channel_list = res.data.item;
        this.columns = res.data.item
      }
    },
    async addChannel(){
      if (this.inputValue.trim()){
        // console.log('渠道')
        const params = {
          name: this.inputValue.trim()
        };
        const resp = await this.$api.others.reqAddChannel(params);
        if (resp.code === 200){
          Toast.success('新建成功！')
          // 更新新建的
          this.newChannelObj = {
            id: resp.data.id,
            name: this.inputValue.trim()
          };
          this._getChannelArr();
        }
      } else {
        Toast('请先输入！')
      }
    },

    clearInputValue(){
      this.inputValue = '';
      this.newChannelObj = {};
    },

    // 切换渠道
    importChannel(){
      this.isSelect = !this.isSelect;
      this.inputValue = '';
      this.value = '';
      this.newChannelObj = {};
      this.selectChannelObj  = {};
    },

    showMyLinkModal(linkStr) {
      Dialog.confirm({
        title: '温馨提示',
        message: `将我的链接复制、粘贴到手机短信、微信朋友圈、QQ空间等各大社交软件，发送给好友注册下载，推广企业用户赚企业提成，推广个人用户赚代招费。我的链接为：${linkStr}`,
        confirmButtonText: '复制链接',
        confirmButtonColor: '#1989FA',
        messageAlign: 'left'
      })
        .then(() => {
          // 点击确定
          this.$copyText(linkStr).then(
            function (e) {
              Toast('复制成功')
            },
            function (e) {
              Toast('复制出错')
            }
          )
        })
        .catch(() => {
          // on cancel
        });
    },

    // 是否带有渠道的
    toGenerateLinkOrCode(isHasChannel = true){

      const paramObj = {
        ...(isHasChannel ? (this.isSelect ? this.selectChannelObj : this.newChannelObj) : {id: '', name: ''}),
        source_type: this.source_type,
      };
      if (this.allUserInfo.id) {
        /*
        * 以前的需求
        * */
        // rpId 是推荐人的id
        // gId 是推荐人的企业的id
        // p 是个人认证 状态
        // g 是企业认证 状态

        /*
        * 2022-03-01 新的需求
        * cId为渠道id,
        * cn为渠道名称,
        * cn为来源类型,
        * */
        const {account, ids, company_id = '', p = 2, certification_state, g = 2, company_certification_state} = this.allUserInfo;
        console.log('是都带有渠道参数', paramObj);
        console.log('ids:'+ids)
        const {id, name, source_type} = paramObj;

        // 更新链接
        const linkUrlStr = this.base_url
          +
          `?company_id=${this.allUserInfo.id}&rpId=${ids}&gId=${company_id}&p=${certification_state}&g=${company_certification_state}&cId=${id}&cn=${name}&st=${source_type}&account=${this.$Base64.encode(account)}`;

        const linkUrlCompany = this.base_url_company
          + `/${this.allUserInfo.id}?company_id=${this.allUserInfo.id}&rpId=${ids}&gId=${company_id}&p=${certification_state}&g=${company_certification_state}&cId=${id}&cn=${name}&st=${source_type}&account=${this.$Base64.encode(account)}&qode=1`

        if (this.source_type === 'L'){
          // 链接地址
          this.showMyLinkModal( encodeURI(linkUrlStr));
        } else {
          // 路径
          const pathUrlObj = {
            'V': 'verticalPoster',
            'H': 'horizontalPoster',
          };
          this.$router.push({
            name: pathUrlObj[this.source_type],
            query: {
              // urlStr: linkUrlStr
              urlStr:linkUrlCompany
            }
          })
        };
      };
    },

    onConfirm(value) {
      console.log('选择哪个', value.id, value.name);
      this.selectChannelObj = {...value};
      this.value = value.name;
      this.showPicker = false;
    },
  },

}
</script>

<style lang="scss" scoped>
.guide_page{
  width: 100%;
  box-sizing: border-box;
}

</style>
